const Koa = require('koa')
const views = require('koa-views')
const serve = require('koa-static')
const Router = require('koa-router')
const IO = require('koa-socket')
const mongoose = require('mongoose')
const models = require('./models.js')
const Tx = require('ethereumjs-tx')
const web3 = require('web3')

const app = new Koa()
const io = new IO()
const router = new Router()

let port = 3000
mongoose.connect('mongodb://127.0.0.1/test', {useMongoClient: true})
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))

io.attach(app);

io.on('message', (ctx, data) => {
  let stock, term, start
  console.log('data event', data)
  ctx.socket.emit( 'message', {
    message: 'response from server'
  })
})

// Template files folder. Must be used before any router is used
app.use(views(__dirname, {
  extension: 'html'
}))

// Static files folder
app.use(serve(__dirname + '/public'))

// router.get('/a/', async ctx => {
//   await ctx.render('index1')
// })

// router.get('/w/', async ctx => {
//   await ctx.render('index2');
// })

// router.get('/api/trend/', async ctx => {
//   // var stock = ctx.query.stock
//   // var term = ctx.query.term
//   // var start = ctx.query.start
//   // var end = ctx.query.end
//   let stock = '002326'
//   let term = 'd'
//   let collection = stock + '.' + term
//   let Trend = mongoose.model(collection, models.trendSchema, collection)
//   let data = await Trend.find()
//     // .where('datetime').gte(start).lte(end)
//     // .sort('datetime')
//     .exec()
//   ctx.body = {data: data, code: 100, msg: 'Successful'}
// })

router.post('/api/order/', async ctx => {
  // var stock = ctx.query.stock
  // var term = ctx.query.term
  // var start = ctx.query.start
  // var end = ctx.query.end

  let keyString = 'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109'
  let txParams = {
    nonce: '0x00',
    gasPrice: '0x09184e72a000',
    gasLimit: '0x2710',
    to: '0x0000000000000000000000000000000000000000',
    value: '0x00',
    data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
  }
  let rawTx = getTx(keyString, txParams)

  // web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
  //   if (!err) {de1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"
  //   }
  //     console.log(hash) // "0x7f9fa
  // })
  ctx.body = {data: null, code: 100, msg: 'Successful'}
})

function getTx(key, txParams) {
  let privateKey = new Buffer(key, 'hex')
  let tx = new Tx(txParams)
  tx.sign(privateKey)
  let serializedTx = tx.serialize()
  return '0x' + serializedTx.toString('hex')
}

router.post('/api/transaction/', async ctx => {
  // var stock = ctx.query.stock
  // var term = ctx.query.term
  // var start = ctx.query.start
  // var end = ctx.query.end
  let stock = '002326'
  let term = 'd'
  let collection = stock + '.' + term
  let Trend = mongoose.model(collection, models.trendSchema, collection)
  let data = await Trend.find()
    // .where('datetime').gte(start).lte(end)
    // .sort('datetime')
    .exec()
  ctx.body = {data: data, code: 200, msg: 'Successful'}
})

router.get('/api/all_event/', async ctx => {
  // let collection = 'event'
  // let Events = mongoose.model(collection, models.eventSchema, collection)
  let data = await models.Event.find().exec()
  ctx.body = {data: data, code: 200, msg: 'Successful'}
})

app.on('error', (err, ctx) => {
  console.log('server error', err, ctx)
})

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(port)
console.log('listening on port ' + port)
